<template>
  <div>
    <div class="login-container">
     
      <div style="position: absolute;left: 0;
      top:0;
      right: 0;
      bottom: 0;width: 100%;height: 0px;">
          <vue-particles
          color="#FFFFFF"
          :particleOpacity="0.7"
          :particlesNumber="80"
          shapeType="circle"
          :particleSize="5"
          linesColor="#FFFFFF"
          :linesWidth="1.5"
          :lineLinked="true"
          :lineOpacity="0.5"
          :linesDistance="150"
          :moveSpeed="3"
          :hoverEffect="true"
          hoverMode="grab"
          :clickEffect="true"
          clickMode="push"
        >
        </vue-particles>
      </div>
   <div style="display:flex;align-items: center;width:100%;justify-content:center">
    <div class="backToimg" >
        <img src="../../assets/img/ob-signin.png" alt="" style="margin:11% 0px  0px 8%"  />
      </div>
    <div class="logingBox">
      <div class="login-wrap">
        <!-- <div class="title-container">
        <h1 class="title">渡石医药物流管理系统</h1>
        <h5 class="loginTexe">医药物流变得安全而简单</h5>
      </div> -->
        <el-tabs v-model="activeName">
          <el-tab-pane name="userlogin">
            <span slot="label"><i class="el-icon-date"></i> 账号登录</span>
            <el-form :model="loginForm" :rules="loginRules" ref="formName" class="loginForm demo-ruleForm"
              auto-complete="on" label-position="left">
              <el-form-item class="mobilebox" prop="accountName">
                <el-input id="username" prefix-icon="el-icon-user-solid" ref="username"
                  v-model.trim="loginForm.accountName" class="inputbox" placeholder="请输入用户名" name="username"
                  maxlength="16" type="text" tabindex="1" auto-complete="on" />
              </el-form-item>
              <el-form-item prop="password">
                <el-input id="password" prefix-icon="el-icon-search" :key="passwordType" ref="password"
                  v-model="loginForm.password" class="inputone" placeholder="请输入密码" show-password :type="passwordType"
                  name="passwod" tabindex="2" maxlength="16" auto-complete="on" @keyup.enter.native="handleLogin" />
              </el-form-item>
              <!-- 随机验证码 -->
              <el-row type="flex">
                <el-form-item prop="param" class="param" style="width: 64%;">
                  <el-input id="auth_code" ref="getValue" v-model="loginForm.param" maxlength="8" placeholder="请输入验证码"
                    @change="submitForm()" />
                </el-form-item>
                <div style="margin-left: 10px;" >
                  <img :src="authcode" alt="" srcset="" style="width: 97px;height: 36px; background: #CCD5F8;padding: 0px 6px 0px 6px;border-radius:5px" @click="refreshCode" />
                </div>
                <!-- <el-form-item>

                  <div class="identifybox" style="margin-top:8px ;">
                    <el-button id="refresh_code" type="text" @click="refreshCode">看不清，换一张</el-button>
                  </div>
                </el-form-item> -->
              </el-row>
              <div class="operation-row" style="padding-bottom: 0px">
                <el-link href="/permission/register" type="danger">立即注册</el-link>
              </div>
              <el-button id="login_button" class="loginBtn" :loading="loading" type="warning" :disabled="disabled"
                @click.native.prevent="AccoutLogin('formName')">登录</el-button>
              <!-- <div class="choicebox">
              <div class="chiceboxOptions">
                提示：忘记密码请用手机号+手机验证码登录，再修改密码！
              </div>
              <el-link v-if="isCut" :underline="false" class="jump" type="primary" @click="addret">平台注册</el-link>
            </div> -->
              <div style="padding-top: 10px">
                <!-- <el-checkbox v-model="checked" class="check"></el-checkbox> -->
                <span class="agreement" style="color: #8e8787">登录即视为同意
                  <a style="color: #fe9400" href="javascript:;" @click="handleShowDialog">《用户隐私协议》</a></span>
              </div>
            </el-form>
          </el-tab-pane>
          <el-tab-pane name="mobile">
            <span slot="label"><i class="el-icon-phone"></i> 手机号登录</span>
            <div class="mobile_box">
              <!-- loginForm -->
              <el-form ref="loginFormMoblie" :model="loginFormMoblie" :rules="loginRulesMoblie" class="loginForm"
                auto-complete="on" label-position="left">
                <!-- <el-form-item class="mobilebox" prop="mobile">
                  <el-input prefix-icon="el-icon-phone-outline" ref="mobile" v-model.trim="loginFormMoblie.mobile"
                    class="inputbox" placeholder="请输入手机号" name="mobile" maxlength="16" type="text" />
                </el-form-item> -->
                <el-input prefix-icon="el-icon-phone-outline" ref="mobile" v-model.trim="loginFormMoblie.mobile"
                    class="inputbox" placeholder="请输入手机号" name="mobile" maxlength="16" type="text" style="margin-bottom:20px" />
          
                <el-row >
                  <el-col :span="16">
                    <div class="verification">
                      <!-- <span>*</span> -->
                      <el-form-item prop="mobile_captcha">
                        <el-input v-model="loginFormMoblie.mobile_captcha" class="ret-authCode" maxlength="8"
                          placeholder="请输入手机验证码" />
                      </el-form-item>
                    </div>
                  </el-col>
                  <el-col :span="3">
                    <el-button :class="{ 'disabled-style': getCodeBtnDisable }" :disabled="getCodeBtnDisable"
                      @click="getCode">{{ codeBtnWord }}
                    </el-button>
                  </el-col>
                </el-row>

                <div class="operation-row" style="padding-bottom: 0px">
                  <el-link href="/permission/register" type="danger">立即注册</el-link>
                </div>
                <el-button style="padding: 7px 15px !important" class="loginBtn" :loading="loading" type="warning"
                  :disabled="disabled" @click.native.prevent="handleLogin('loginFormMoblie')">登录</el-button>
                <div style="padding-top: 10px">
                  <!-- <el-checkbox  v-model="checked" class="check"></el-checkbox> -->
                  <span class="agreement" style="color: #8e8787">登录即视为同意
                    <a style="color: #fe9400" href="javascript:;" @click="handleShowDialog">《用户隐私协议》</a></span>
                </div>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
   </div>

  </div>
  <div>
    <Agreement type="secret" :visible="agreementDialog" @close="handleCloseDialog"></Agreement>
  </div>

  </div>
 
</template>
<script>
  import { login, random, getMobile } from "@/api/user";
  import Agreement from "./components/agreement.vue";

  import { setToken, getToken } from "@/utils/auth";
  import cookie from "js-cookie";
  import md5 from "js-md5";
  import "./index.scss";
  import Vue from "vue";

  export default {
    name: "Login",
    components: {
      Agreement,
    },
    data() {
      return {
        activeName: "userlogin",
        waitTime: 61, // 获取验证码按钮失效时间
        codeBtnWord: "获取验证码", // 获取验证码按钮文字
        alterrandom: true, // 默认隐藏验证码
        random: "", // 随机数图片
        authcode: "", //验证码
        // 下拉框数据
        options: [
          {
            value: "1",
            label: "用户登录",
          },
          {
            value: "2",
            label: "发货方查货登录",
          },
        ],
        // 下拉框的内容
        value: "",
        // 账号密码
        loginForm: {
          accountName: "",
          password: "",
          param: "", // 输入的验证码
          code: "", //生成验证码的唯一标识
        },
        // 账号密码验证
        loginRules: {
          // accountName: [
          //   { required: true, message: "请输入姓名", trigger: "blur" },
          // ],
          // password: [
          //   { required: true, trigger: "blur", message: "密码不能为空" },
            // {
            //   required: true,
            //   pattern: /^(?=.*[0-9].*)(?=.*[A-Za-z].*).{6,18}$/,
            //   message: "请输入6-18位的大字母或小写字母和数字",
            //   trigger: "blur",
            // },
          // ],
          // param: [
          //   { required: true, trigger: "blur", message: "验证码不能为空" },
          //   { min: 4, max: 8, message: "验证码必须4到8位", trigger: "blur" },
          // ],
        },
        loginFormMoblie: {
          mobile: "",
          mobile_captcha: "",
        },
        loginRulesMoblie: {
          // mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }],
          // mobile_captcha: [
          //   { required: true, message: "请输入手机验证码", trigger: "blur" },
          // ],
        },
        loading: false,
        passwordType: "password",
        redirect: undefined,
        // 注册按钮默认显示
        isCut: true,
        // 登录按钮禁用 后续 验证通过为false
        disabled: false,
        checked: false,
        agreementDialog: false,
        screenHeight:"",
      };
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true,
      },
    },
    computed: {
      // 用于校验手机号码格式是否正确
      phoneNumberStyle() {
        const reg = /^1[3456789]\d{9}$/;
        if (!reg.test(this.loginFormMoblie.mobile)) {
          return false;
        }
        return true;
      },
      // 控制获取验证码按钮是否可点击
      getCodeBtnDisable: {
        get() {
          if (this.waitTime === 61) {
            const reg = /^1[3456789]\d{9}$/;
            if (
              reg.test(this.loginFormMoblie.mobile) &&
              this.loginFormMoblie.mobile.length === 11
            ) {
              return false;
            }
            return true;
          }
          return false;
        },
        // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
        set() { },
      },
    },
    created() {
      this.getrandom(); // 页面打开调用
      // 获取随机数
    },
    updated() {
      let screenHeight = document.body.clientHeight
      let particlesCanvas = document.getElementsByTagName("canvas")[0];
      particlesCanvas.style.height = screenHeight-10 + "px";
    },
    mounted() {
    },
    methods: {
      getrandom() {
        random().then((res) => {
          // 生成验证码图片
          var baser = res.data.captcha;
          this.authcode = baser;
          // 获取到验证码的唯一标识登录的时候将唯一标识传递回去
          this.loginForm.code = res.data.id;
        });
      },
      //隐私协议弹窗展示
      handleShowDialog() {
        this.agreementDialog = true;
      },
      //隐私协议弹窗关闭
      handleCloseDialog() {
        this.agreementDialog = false;
      },
      submitForm() {
        // 输入的验证码
        this.loginForm.param = this.$refs.getValue.value;
      },
      refreshCode() {
        // 点击换一张
        this.getrandom();
      },
      // 点击切换
      addret() {
        this.$router.push("/ret");
      },
      // 密码验证
      showPwd() {
        if (this.passwordType === "password") {
          this.passwordType = "";
        } else {
          this.passwordType = "password";
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },
      // 手机号登录
      handleLogin(loginRulesMoblie) {
        if(this.loginFormMoblie.mobile != "" && this.loginFormMoblie.mobile_captcha != "" ) {
          const formData = new FormData();
        formData.append("login_method", "mobile"); //指用手机验证码登录
        formData.append("mobile", this.loginFormMoblie.mobile);
        formData.append("sms_code", this.loginFormMoblie.mobile_captcha);
        formData.append("login_channel", "1");
        // this.Login_Fution(formData);
        this.$refs[loginRulesMoblie].validate((valid) => {
          if (valid) {
            this.Login_Fution(formData);
          } else {
            // console.log("error submit!!");
            return false;
          }
        });
        }else {
          if( this.loginFormMoblie.mobile == "") {
            this.openwaring("请输入手机号")
          }else if (this.loginFormMoblie.mobile_captcha == "") {
            this.openwaring("请输入验证码")
          }
        }
      
      },
      // 账号密码登录
      AccoutLogin(formName) {
        if(this.loginForm.accountName != "" &&  this.loginForm.password != "" && this.loginForm.param !="" ) {
        const formData = new FormData();
        formData.append("login_method", "password"); //指用账号密码登录
        formData.append("username", this.loginForm.accountName);
        formData.append("password", md5(this.loginForm.password));
        formData.append("captcha", this.loginForm.param);
        formData.append("captcha_id", this.loginForm.code);
        formData.append("login_channel", "1");
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.Login_Fution(formData);
          } else {
            return false;
          }
        });
        }else {
          if(this.loginForm.accountName == "") {
            this.openwaring("请输入用户名")
          }else if (this.loginForm.password == "") {
            this.openwaring("请输入密码")
          }else if (this.loginForm.param == "") {
            this.openwaring("请输入验证码")
          }
        }
       
      },
      // 登录函数
      Login_Fution(formData) {
        login(formData).then((res) => {
          // console.log(res.data);
          localStorage.setItem(
            "user_id",
            JSON.stringify(res.data.current_user.user_id)
          );
          setToken("Token", res.data.token);

          let type = (res.data.current_user || {}).user_type;
          if (type === 2 || type === 3) {
            this.$router.push({ path: "/infoManage/userCenter" });
          } else {
            this.$router.push({ path: "/" });
          }
          this.$store.dispatch("initLeftMenu");
          localStorage.setItem(
            "allUserInfo",
            JSON.stringify(res.data.all_user_info)
          );
          Vue.prototype.$socket.connect();
        });
      },
      // 点击切换  隐藏注册按钮
      CutSelect() {
        if (this.value === "1") {
          this.isCut = true;
        } else {
          this.isCut = false;
        }
      },
      // 发送验证码
      getCode() {
        if (this.phoneNumberStyle) {
          // 调用获取短信验证码接口

          getMobile({ phone: this.loginFormMoblie.mobile }).then((res) => {
            this.$message({
              message: "验证码已发送，请稍候...",
              type: "success",
              center: true,
            });
          });
          // 因为下面用到了定时器，需要保存this指向
          const that = this;
          that.waitTime--;
          that.getCodeBtnDisable = true;
          this.codeBtnWord = `${this.waitTime}s 后重新获取`;
          const timer = setInterval(function () {
            if (that.waitTime > 1) {
              that.waitTime--;
              that.codeBtnWord = `${that.waitTime}s 后重新获取`;
            } else {
              clearInterval(timer);
              that.codeBtnWord = "获取验证码";
              that.getCodeBtnDisable = false;
              that.waitTime = 61;
            }
          }, 1000);
        }
      },
      openwaring(message) {
        this.$message({
            message: message,
            type: 'warning'
          });
      }
    },
  };
</script>
<style lang="less" scoped>
  /deep/.mobile_box .el-form-item {
    float: left !important;
    width: 100% !important;
  }
  .el-button:hover {
    background: #D48D8D !important;
    opacity: 0.5;
   
    font-weight: bold;
    border: none;

  }
  /deep/.mobile_box .el-button--mini,
  /deep/.mobile_box.el-button--mini.is-round {
    padding: 11px 15px !important;
    margin-left: 5px;
  }
  /deep/.el-tabs__item.is-active {
    color: #F09937 !important;
  }
  /deep/.el-tabs__item.is-active:hover {
    color: #F09937 !important;
  }
  /deep/.el-tabs__active-bar {
    background: #E4E7ED;
  }
  /deep/.mobile_box .verification .el-input__inner {
    padding-left: 10px !important;
  }
  .mobile_box .verification span {
    display: block;
    float: left;
    margin-right: 5px;
    line-height: 45px;
    color: #ff0000;
  }

  /deep/.check .el-checkbox__input.is-checked .el-checkbox__inner,
  .check .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #f09937 !important;
    border-color: #f09937 !important;
  }

  /deep/.check .el-checkbox__inner {
    border-color: #dcdfe6 !important;
  }

  /deep/.check .el-checkbox__inner:hover {
    border-color: #f09937 !important;
  }
</style>